﻿using System;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using Caramel;

namespace Caramel.Web.Http.Filters
{
    public class UnitOfWorkFilterAttribute : ActionFilterAttribute
    {
        private IUnitOfWork UnitOfWork { get; set; }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            this.UnitOfWork = Caramel.UnitOfWork.Begin();
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception == null)
            {
                this.UnitOfWork.Commit();
            }
            else
            {
                this.UnitOfWork.Rollback();
            }

            this.UnitOfWork.Dispose();
        }
    }
}